/*
 * @Author: duanguang
 * @Date: 2022-03-03 09:55:15
 * @LastEditTime: 2022-04-29 15:16:04
 * @LastEditors: duanguang
 * @Description: 
 * @FilePath: /legions-server/app/controller/branch_merge_request.ts
 * 「扫去窗上的尘埃，才可以看到窗外的美景。」
 */
import ResponseModel,{ PageResponseModel } from '@/model/responseModel';
import { UserRoleEnum,auditStatusEnum } from '@/constants/enum.types';
import { roleAuthority } from '@/abstract/controller/decorators';
import CommonController from '@/abstract/controller/common';
import { HttpClientResponse } from 'urllib';
export default class BranchMergeRequestController extends CommonController {
    /** 分支合并申请通过*/
    @roleAuthority(UserRoleEnum.developer)
    public async approved() {
        const { body } = this.ctx.request;
        const result = await this.ctx.model.BranchMergeRequest.findById(body.id)
        if (result && result.assign_members_id === this.userInfo?.id) {
            const project_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${result.gitlab_project_id}/merge_requests/${result.merge_request_iid}/merge`,{
                dataType: 'json',
                contentType: 'application/json',
                method: 'PUT',
                headers: {
                    Authorization: this.ctx.request.get('gitlab_authorization')
                },
            });
            if (project_result.data && project_result.data['iid']) {
                await this.ctx.service.branchMergeRequest.approved({
                    id: body.id || '',
                    userId: this.userInfo?.id || '',
                });
                this.ctx.body = new ResponseModel({
                    success: true,
                    data: project_result.data,
                    message: '合并请求处理完成',
                });
                return
            }
            this.ctx.body = new ResponseModel({
                success: false,
                data: project_result.data,
                message: '合并请求处理失败',
            });
        }
        this.ctx.body = new ResponseModel({
            success: false,
            data: null,
            message: '合并请求处理失败:可能未找到需要受理的合并请求',
        });
    }
    /** 分支合并申请*/
    @roleAuthority(UserRoleEnum.developer)
    public async create() {
        const { ctx } = this;
        const { body } = ctx.request;
        const errors = this.app.validator.validate(
            {
                repository_name: { type: 'string',required: true },
                project_id: { type: 'string',required: true },
                source_branch: { type: 'string',required: true },
                target_branch: { type: 'string',required: true },
                merge_title: { type: 'string',required: true },
                gitlab_project_group: { type: 'string',required: true },
                gitlab_project_id: { type: 'string',required: true },
                repository_https: { type: 'string',required: true },
                merge_description: { type: 'string',required: true },
                reviewer_members_id: { type: 'string',required: true },
                reviewer_members: { type: 'string',required: true },
                assign_members: { type: 'string',required: true },
                assign_members_id: { type: 'string',required: true },
                assign_members_gitlab_id: { type: 'string',required: true },
                reviewer_members_gitlab_id: { type: 'string',required: true },
            },
            body,
        )
        if (errors) {
            this.ctx.body = new ResponseModel({
                success: false,
                data: errors,
                message: '参数错误',
            });
            return;
        }
        try {
            const merge_request_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${body.gitlab_project_id}/merge_requests`,{
                dataType: 'json',
                contentType: 'application/json',
                method: 'POST',
                headers: {
                    Authorization: this.ctx.request.get('gitlab_authorization')
                },
                data: {
                    source_branch: body.source_branch,
                    target_branch: body.target_branch,
                    title: body.merge_title,
                    assignee_id: parseInt(body.assign_members_gitlab_id),
                    reviewer_ids: [parseInt(body.reviewer_members_gitlab_id)],
                    description: body.merge_description,
                },
            });
            if (merge_request_result.data && merge_request_result.data['title']) {
                const res = await this.ctx.service.branchMergeRequest.create({
                    ...body,
                    creator_id: this.userInfo?.id,
                    creator: this.userInfo?.name,
                    merge_request_iid: merge_request_result.data['iid'],
                    audit_status: auditStatusEnum.waiting,
                });
                this.ctx.body = new ResponseModel({
                    success: true,
                    data: res,
                    message: '分支合并申请发起成功',
                });
                return
            }
            this.ctx.body = new ResponseModel({
                success: false,
                data: null,
                message: `分支合并申请发起失败(${merge_request_result.data})`,
            });
        } catch (error) {
            this.ctx.body = new ResponseModel({
                success: false,
                // @ts-ignore
                message: error && error.toString(),
            });
        }
    }

    @roleAuthority(UserRoleEnum.developer)
    public async update() {
        const { ctx } = this;
        const { body } = ctx.request;
        const errors = this.app.validator.validate(
            {
                target_branch: { type: 'string',required: true },
                id: { type: 'string',required: true },
                gitlab_project_id: { type: 'string',required: true },
                merge_request_iid: { type: 'number',required: true },
                merge_title: { type: 'string',required: true },
                merge_description: { type: 'string',required: true },
                reviewer_members_id: { type: 'string',required: true },
                reviewer_members: { type: 'string',required: true },
                assign_members: { type: 'string',required: true },
                assign_members_id: { type: 'string',required: true },
                assign_members_gitlab_id: { type: 'string',required: true },
                reviewer_members_gitlab_id: { type: 'string',required: true },
            },
            body,
        )
        if (errors) {
            this.ctx.body = new ResponseModel({
                success: false,
                data: errors,
                message: '参数错误',
            });
            return;
        }
        try {
            const merge_request_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${body.gitlab_project_id}/merge_requests/${body.merge_request_iid}`,{
                dataType: 'json',
                contentType: 'application/json',
                method: 'PUT',
                headers: {
                    Authorization: this.ctx.request.get('gitlab_authorization')
                },
                data: {
                    target_branch: body.target_branch,
                    title: body.merge_title,
                    assignee_id: parseInt(body.assign_members_gitlab_id),
                    reviewer_ids: [parseInt(body.reviewer_members_gitlab_id)],
                    description: body.merge_description,
                },
            });
            if (merge_request_result.data && merge_request_result.data['title']) {
                const res = await this.ctx.service.branchMergeRequest.edit({
                    ...body,
                    userId: this.userInfo?.id,
                });
                if (res) {
                    this.ctx.body = new ResponseModel({
                        success: true,
                        data: res,
                        message: '分支合并申请数据更新成功',
                    });
                    return
                }
            }
            this.ctx.body = new ResponseModel({
                success: false,
                data: null,
                message: `分支合并申请更新失败(${JSON.stringify(merge_request_result.data)})`,
            });
        }
        catch (error) {
            this.ctx.body = new ResponseModel({
                success: false,
                // @ts-ignore
                message: error && error.toString(),
            });
        }
    }

    @roleAuthority(UserRoleEnum.developer)
    public async delete() {
        const { ctx } = this;
        const { body } = ctx.request;
        const errors = this.app.validator.validate({
            gitlab_project_id: { type: 'string',required: true },
            merge_request_iid: { type: 'number',required: true },
        },body)
        if (errors) {
            this.ctx.body = new ResponseModel({
                success: false,
                data: errors,
                message: '参数错误',
            });
            return;
        }
        try {
            const delete_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${body.gitlab_project_id}/merge_requests/${body.merge_request_iid}`,{
                dataType: 'json',
                contentType: 'application/json',
                method: 'DELETE',
                headers: {
                    Authorization: this.ctx.request.get('gitlab_authorization')
                },
                data: {
                    id: body.gitlab_project_id,
                    merge_request_iid: body.merge_request_iid,
                },
            });
            if (delete_result) {
                this.ctx.body = new ResponseModel({
                    success: true,
                    data: null,
                    message: '删除成功',
                });
            }
        }
        catch (error) {

        }
    }
    /**
     * 分支申请数据列表
     */
    @roleAuthority(UserRoleEnum.developer)
    public async list() {
        const query = this.ctx.query as any;
        try {
            const res = await this.ctx.service.branchMergeRequest.getList({
                ...query,
                userRule: this.userInfo?.roleNo,
                userId: this.userInfo?.id,
            })
            this.ctx.body = new PageResponseModel({
                success: true,
                message: '查询成功',
                data: res,
            });
        } catch (error) {
            this.ctx.body = new PageResponseModel({
                success: false,
                // @ts-ignore
                message: error && error.toString(),
            });
        }
    }
}
